import { ref } from 'vue'

const toasts = ref([])
let seed = 0

function show(message, options = {}){
  const id = ++seed
  const toast = {
    id,
    message,
    type: options.type || 'success', // success | info | error
    duration: typeof options.duration === 'number' ? options.duration : 2200,
  }
  toasts.value.push(toast)
  if (toast.duration > 0){
    setTimeout(() => dismiss(id), toast.duration)
  }
  return id
}

function dismiss(id){
  const i = toasts.value.findIndex(t => t.id === id)
  if (i > -1) toasts.value.splice(i, 1)
}

const api = {
  toasts,
  show,
  dismiss,
  success(msg, duration){ return show(msg, { type: 'success', duration }) },
  info(msg, duration){ return show(msg, { type: 'info', duration }) },
  error(msg, duration){ return show(msg, { type: 'error', duration }) },
}

export default api